package cn.tnar.utils;

import cn.tnar.constant.ResultCode;
import cn.tnar.response.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @Author: 陈亮
 * @Date: 2018/10/11 22:53
 */
public class JwtUtil {

    public static final long EXPIRATION_TIME = 7200000L; // 2 hour 有效期
    public static final String SECRET = "chenliang";//  密钥

    //生成
    public static String createJWT(String userId, String userName) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //当前时间
        long nowMillis = System.currentTimeMillis();
        System.out.println("nowMillis:" + nowMillis);
        Date now = new Date(nowMillis);
        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("type", "JWT")
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        long expMillis = nowMillis + EXPIRATION_TIME;
        System.out.println("expMillis:" + expMillis);
        Date exp = new Date(expMillis);
        builder.setExpiration(exp).setNotBefore(now);
        //生成JWT
        String jwtTokenStr = builder.compact();
        return jwtTokenStr;
    }

    //解析
    public static Result parseJWT(String jsonWebToken) {
        Result result = new Result();
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
                    .parseClaimsJws(jsonWebToken).getBody();
            result.setResultCode(ResultCode.SUCCESS);
        } catch (Exception ex) {
            result.setResultCode(ResultCode.PERMISSION_NO_ACCESS);
        }
        result.setData(null);
        return result;
    }

    //和时间有关的token
    public static String generateToken(Long id, Date loginTime) {
        return MD5Util.encode(id + (loginTime == null ? 0L : Math.round(loginTime.getTime() / 1000.0)) + SECRET);
    }
}
